package com.project;

import com.project.config.WebMvcConfig;
import com.project.filter.CharFilter;
import com.project.filter.LoginFilter;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

/**
 * @author lyl
 * description:
 */
public class Start7 {
    public static void main(String[] args) {
        new Start7();
    }

    public Start7() {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();
        Context context = tomcat.addContext("", null);

        //使用路径映射的方式进行同一过滤
        this.registerFilter(context, new LoginFilter(), "/html/filter/*");
        this.registerFilter(context, new CharFilter(), "/*");

        WebApplicationContext wac = createApplicationContext(context.getServletContext());
        //创建前端控制器对象
        DispatcherServlet ds = new DispatcherServlet(wac);
        Wrapper wa = Tomcat.addServlet(context, "ds", ds);
        wa.setLoadOnStartup(0);
        wa.addMapping("/*");
        try {
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建SpringMvc的应用上下文
     *
     * @param servletContext
     * @return
     */
    public static WebApplicationContext createApplicationContext(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);
        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    /**
     * 注册过滤器
     *
     * @param context   上下文
     * @param filterObj 过滤器对象
     * @param url       过滤的url地址
     */
    private void registerFilter(Context context, Filter filterObj, String url) {
        //设置过滤器
        FilterDef fd = new FilterDef();
        fd.setFilter(filterObj);
        fd.setFilterName(filterObj.getClass().getName());

        FilterMap fm = new FilterMap();
        fm.setFilterName(filterObj.getClass().getName());
        //设置过滤器的应用范围
        fm.addURLPattern(url);
        //注册过滤器
        context.addFilterDef(fd);
        context.addFilterMap(fm);
    }
}
